package org.unei.common.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

/**
 * Created by sunlei on 2015/7/16.
 */
public class BeanHelper {
    /**
     * 对象转换为map
     * @param target
     * @param props
     * @return
     */
    public static boolean getProperties(Object target, Map props) {

        boolean rc = false;
        if (target == null) {
            throw new IllegalArgumentException("target was null.");
        }
        if (props == null) {
            throw new IllegalArgumentException("props was null.");
        }

        Class clazz = target.getClass();
        Method[] methods = clazz.getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            String name = method.getName();
            Class type = method.getReturnType();
            Class params[] = method.getParameterTypes();
            if ((name.startsWith("is") || name.startsWith("get")) && params.length == 0 && type != null) {

                try {

                    Object value = method.invoke(target);
                    if (value == null) {
                        continue;
                    }

                    if (name.startsWith("get")) {
                        name = name.substring(3, 4).toLowerCase(Locale.ENGLISH)
                                + name.substring(4);
                    } else {
                        name = name.substring(2, 3).toLowerCase(Locale.ENGLISH)
                                + name.substring(3);
                    }

                    props.put( name, value);
                    rc = true;
                } catch (Throwable ignore) {
                }

            }
        }

        return rc;
    }

    /**
     * 将map转换为object
     * @param target
     * @param props
     * @return
     */
    public static boolean setProperties(Object target, Map<String, ?> props) {
        boolean rc = false;
        if (target == null) {
            throw new IllegalArgumentException("target was null.");
        }
        if (props == null) {
            throw new IllegalArgumentException("props was null.");
        }

        for (Iterator<String> iter = props.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            Object value = props.get(name);
            if (setProperty(target, name, value)) {
                iter.remove();
                rc = true;
            }
        }
        return rc;
    }

    public static boolean setProperty(Object target, String name, Object value) {
        try {
            Class clazz = target.getClass();
            Method setter = findSetterMethod(clazz, name);
            if (setter == null) return false;

            if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
                setter.invoke(target, value);
            } else {
                setter.invoke(target, convert(value, setter.getParameterTypes()[0]));
            }
            return true;
        } catch (Throwable ignore) {
            return false;
        }
    }

    public static Method findSetterMethod(Class clazz, String name) {
        name = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
        Method[] methods = clazz.getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            Class params[] = method.getParameterTypes();
            if (method.getName().equals(name) && params.length == 1)
                return method;
        }

        return null;
    }

    public static Object convert(Object value, Class to) {
        if (value == null) {
            if (boolean.class.isAssignableFrom(to)) {
                return Boolean.FALSE;
            }

            return null;
        }

        if (to.isAssignableFrom(value.getClass())) {
            return to.cast(value);
        }

        TypeConversionSupport.Converter converter = TypeConversionSupport.lookupConverter(value.getClass(), to);
        if (converter != null) {
            return converter.convert(value);
        } else {
            throw new IllegalArgumentException("Cannot convert from " + value.getClass()
                    + " to " + to + " with value " + value);
        }
    }

}
